import React, { useEffect, useRef, useState, useLayoutEffect } from 'react';
import * as d3 from 'd3';
import { wrap } from 'comlink';
import { storage } from '../utils/storage';

// Worker导入方式
// @ts-ignore
const worker = wrap(new Worker(new URL('../workers/dataWorker.ts', import.meta.url), { type: 'module' }));

interface RelationGraphProps {
  width?: number;
  height?: number;
  onNodeClick?: (node: any) => void;
}

export const RelationGraph: React.FC<RelationGraphProps> = ({
  width = 800,
  height = 600,
  onNodeClick
}) => {
  const svgRef = useRef<SVGSVGElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const [data, setData] = useState<{ nodes: any[]; edges: any[] } | null>(null);
  const [loading, setLoading] = useState(true);
  const [dimensions, setDimensions] = useState({ width: width, height: height });

  // 自适应容器大小
  useLayoutEffect(() => {
    if (containerRef.current) {
      const { width, height } = containerRef.current.getBoundingClientRect();
      setDimensions({
        width: width || 800,
        height: height || 600
      });
    }

    const handleResize = () => {
      if (containerRef.current) {
        const { width, height } = containerRef.current.getBoundingClientRect();
        setDimensions({
          width: width || 800,
          height: height || 600
        });
      }
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  useEffect(() => {
    const loadData = async () => {
      try {
        // 获取示例数据
        const response = await fetch('/src/data/herbs.json');
        const herbsData = await response.json();
        const herbs = Object.values(herbsData);
        
        // 获取关系数据
        const relResponse = await fetch('/src/data/relations.csv');
        const relationsText = await relResponse.text();
        const relations = relationsText.split('\n')
          .slice(1) // 跳过标题行
          .filter(line => line.trim() !== '')
          .map(line => {
            const [source, target, type, strength] = line.split(',');
            return { source, target, type, strength: parseFloat(strength) };
          });
        
        // 使用 Web Worker 处理布局
        const processedData = await worker.processLayout(herbs, relations);
        setData(processedData);
      } catch (error) {
        console.error('Failed to load data:', error);
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, []);

  useEffect(() => {
    if (!data || !svgRef.current) return;

    const svg = d3.select(svgRef.current);
    svg.selectAll('*').remove();

    // 创建缩放行为
    const zoom = d3.zoom()
      .scaleExtent([0.1, 4])
      .on('zoom', (event) => {
        g.attr('transform', event.transform);
      });

    svg.call(zoom as any);

    const g = svg.append('g');

    // 绘制边
    g.selectAll('line')
      .data(data.edges)
      .enter()
      .append('line')
      .attr('stroke', '#999')
      .attr('stroke-width', 1)
      .attr('x1', (d: any) => d.source.x)
      .attr('y1', (d: any) => d.source.y)
      .attr('x2', (d: any) => d.target.x)
      .attr('y2', (d: any) => d.target.y);

    // 绘制节点
    const nodes = g.selectAll('circle')
      .data(data.nodes)
      .enter()
      .append('g')
      .attr('transform', (d: any) => `translate(${d.x},${d.y})`)
      .style('cursor', 'pointer');

    nodes.append('circle')
      .attr('r', 6)
      .attr('fill', (d: any) => {
        // 根据药材分类设置不同颜色
        const categoryColors: Record<string, string> = {
          '草部': '#4CAF50',
          '木部': '#8D6E63',
          '果部': '#FF9800',
          '菌部': '#9C27B0',
          '石部': '#607D8B'
        };
        
        return categoryColors[d.category] || '#2196F3';
      })
      .style('stroke', '#fff')
      .style('stroke-width', 1.5)
      .on('click', (event, d: any) => {
        event.stopPropagation(); // 阻止事件冒泡
        if (onNodeClick) onNodeClick(d);
      });

    nodes.append('text')
      .attr('dy', 15)
      .attr('text-anchor', 'middle')
      .text((d: any) => d.name)
      .style('font-size', '12px')
      .style('cursor', 'pointer')
      .style('fill', '#333')
      .on('click', (event, d: any) => {
        event.stopPropagation(); // 阻止事件冒泡
        if (onNodeClick) onNodeClick(d);
      });

    // 初始化缩放位置
    svg.call(zoom.transform as any, d3.zoomIdentity.scale(0.8).translate(dimensions.width / 3, dimensions.height / 3));
  }, [data, onNodeClick, dimensions]);

  if (loading) {
    return (
      <div className="loading">
        <div className="loading-spinner"></div>
        <p>正在加载关系图谱...</p>
      </div>
    );
  }

  return (
    <div ref={containerRef} style={{ width: '100%', height: '500px' }}>
      <svg
        ref={svgRef}
        width={dimensions.width}
        height={dimensions.height}
        style={{ 
          border: '1px solid var(--border-color)', 
          borderRadius: 'var(--border-radius)',
          background: 'white',
          width: '100%',
          height: '100%'
        }}
      />
    </div>
  );
}; 